package org.example.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.entity.Gowuche;
import org.example.entity.Product;
import org.example.entity.Shanpin;
import org.example.mapper.Gowuchemapper;
import org.example.mapper.Shanjiamapper;
import org.example.mapper.Shanpinmapper;
import org.example.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GowucheService {
    @Autowired
    Gowuchemapper gowuchemapper;
    @Autowired
    Shanpinmapper shanpinmapper;

    /**
     * 新增购物车
     * @param gowuche
     */
    public void xz(Gowuche gowuche) {

        String jsonString = gowuche.getSelectedSpecs();
        try {
            // 创建 ObjectMapper 对象
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(jsonString);

            StringBuilder resultBuilder = new StringBuilder();

            // 遍历 JSON 对象的每个键值对
            rootNode.fields().forEachRemaining(entry -> {
                JsonNode node = entry.getValue();
                String category = node.get("category").asText();
                String value = node.get("value").asText();

                // 提取 value 中括号前的内容
                int index = value.indexOf(')');    // 查找右括号的位置
                String result = value.substring(index + 1);  // 从右括号后一位开始截取字符串


                resultBuilder.append(category).append("：").append(result).append(" ");
            });

            // 去掉最后一个多余的空格，并将结果转换为字符串
            String resultString = resultBuilder.toString().trim();

            gowuche.setSelectedSpecs(resultString);

        } catch (Exception e) {
            e.printStackTrace();
        }

        Gowuche gowucheList=gowuchemapper.cx(gowuche.getProductId(),gowuche.getSelectedSpecs());
        if(gowucheList==null){
            Shanpin shanpin=shanpinmapper.cxid(Math.toIntExact(gowuche.getProductId()));
            gowuche.setDianpuusername(shanpin.getUsername());
            Product product=shanpinmapper.cxproduct(shanpin.getId());
            gowuche.setFanhuodi(product.getLocation());
            gowuchemapper.xz(gowuche);
        }else{
            gowuchemapper.xg(gowucheList.getId());
        }

    }

    /**
     * 购物车查询
     * @param username
     */
    public List<Gowuche> cx(String username) {

        return gowuchemapper.cxs(username);
    }

    /**
     * 删除
     * @param id
     */
    public void sc(int id) {
        gowuchemapper.sc(id);
    }

    /**
     * 注销
     * @param username
     */
    public void zxsc(String username) {
        gowuchemapper.zx(username);
    }
}
